/*
* 
* @license	Apache License 2.0
* @author	Eugene Kuznetsov
*
*/

#include <memory>
#include "CDataBuffer.hpp"

CDataBuffer::CDataBuffer()
	: m_pData(0)
	, m_nSize(0)
{
	DBG_L4(("[%p] %s()\n", this, __FUNCTION__));
}

CDataBuffer::CDataBuffer(Chr* buffer)
	: m_pData(0)
	, m_nSize(0)
{
	DBG_L4(("[%p] %s(Chr*)\n", this, __FUNCTION__));
	Int16 length = strlen(buffer);
	m_nSize = ToUInt32(length);
	if (m_nSize != 0)
	{
		DBG_L4(("[%p:%d] size = %d\n", this, __LINE__, length));
		m_pData = new UChr[m_nSize + 1];
		m_pData[m_nSize] = 0;
		DBG_L4(("[%p:%d] new %p\n", this, __LINE__, m_pData));
		memcpy(m_pData, buffer, m_nSize);
	}
	else
	{
		DBG_L4(("[%p:%d] size == 0\n", this, __LINE__));
	}
}

CDataBuffer::CDataBuffer(UChr* buffer, UInt32 size)
	: m_pData(0)
	, m_nSize(size)
{
	DBG_L4(("[%p] %s(UChr*, UInt32)\n", this, __FUNCTION__));
	if (size != 0)
	{
		DBG_L4(("[%p:%d] size = %d\n", this, __LINE__, size));
		m_pData = new UChr[size + 1];
		m_pData[size] = 0;
		DBG_L4(("[%p:%d] new %p\n", this, __LINE__, m_pData));
		memcpy(m_pData, buffer, size);
	}
	else
	{
		DBG_L4(("[%p:%d] size == 0\n", this, __LINE__));
	}
}

CDataBuffer::CDataBuffer(const CDataBuffer& DataBuffer)
	: m_pData(0)
	, m_nSize(0)
{
	DBG_L4(("[%p] %s(CDataBuffer&)\n", this, __FUNCTION__));
	append(const_cast<UChr*>(DataBuffer.data()), DataBuffer.size());
}

CDataBuffer::~CDataBuffer()
{
	DBG_L4(("[%p] %s\n", this, __FUNCTION__));
	if (m_pData != 0)
	{
		DBG_L4(("[%p:%d] delete %p\n", this, __LINE__, m_pData));
		delete [] m_pData;
	}
}

const UChr * CDataBuffer::data() const
{
	return m_pData;
}

UInt32 CDataBuffer::size() const
{
	return m_nSize;
}

void CDataBuffer::append(Chr* buffer)
{
	DBG_L4(("[%p] %s(Chr*)\n", this, __FUNCTION__));
	Int16 length = strlen(buffer);
	append(reinterpret_cast<UChr*>(buffer), ToUInt32(length));
}

void CDataBuffer::append(UChr* buffer, UInt32 size)
{
	DBG_L4(("[%p] %s(UChr*, UInt32)\n", this, __FUNCTION__));
	if (size == 0)
	{
		return;
	}
	if (m_pData == 0)
	{
		m_pData = new UChr[size + 1];
		m_pData[size] = 0;
		memcpy(m_pData, buffer, size);
		m_nSize = size;
		return;
	}
	CDataBuffer temp_buffer(m_pData, m_nSize);
	delete [] m_pData;
	m_pData = new UChr[m_nSize + size + 1];
	m_pData[m_nSize + size] = 0;
	memcpy(m_pData, temp_buffer.data(), temp_buffer.size());
	memcpy(m_pData + temp_buffer.size(), buffer, size);
	m_nSize += size;
}

void CDataBuffer::clear()
{
	DBG_L4(("[%p] %s\n", this, __FUNCTION__));
	if (m_pData == 0)
	{
		return;
	}
	delete [] m_pData;
	m_pData = 0;
	m_nSize = 0;
}
